package cn.yili12.business.interceptor;

import cn.yili12.business.entity.UserDb;
import cn.yili12.business.service.UserService;
import cn.yili12.business.vo.Result;
import cn.yili12.common.thread.AgentThreadLocal;
import cn.yili12.common.util.JwtUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            String token_ = request.getHeader("token_");
            if (StringUtils.isEmpty(token_)) {
                return writeNoLogin(response);
            }
            String username = JwtUtil.getUser(token_);
            UserDb loginUser = userService.getById(Long.valueOf(username));
            if (null == loginUser) {
                return writeNoLogin(response);
            }
            if (!JwtUtil.verify(token_, String.valueOf(loginUser.getId()), loginUser.getPassword())) {
                return writeNoLogin(response);
            }
            AgentThreadLocal.set(loginUser);
            return true;
        } catch (Exception e) {
            log.error("判断是否登录报错", e);
        }
        return writeNoLogin(response);
    }

    private boolean writeNoLogin(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        Result result = new Result(false, "请登录", null, Result.LOGIN);
        String json = JSON.toJSONString(result);
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(response.getOutputStream());
            writer.write(json);
            writer.flush();
        } catch (IOException e) {
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
            }
        }
        return false;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
//         System.out.println("执行了TestInterceptor的postHandle方法");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        System.out.println("执行了TestInterceptor的afterCompletion方法");
    }

}
